const app = getApp();
let deviceId = "";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    seeDetails: true,
    order_id: 0,
    coupon_id: 0,   //优惠卷id
    order: {},
    store_label:[],
    clock_time:0,//时间戳
    lock_code:'',
    use_end_time:'',
    mac_code:'',
    room_password:'',

    constantly_price:0,
    constantly_hour:0,
    price:0,
    showModalStatus:false,   //弹出页面
    //定时器
    payinterval:null,
    interval:null,
    keyInfo: {}, // 钥匙数据
    lock_state:false,
    fw_status:true,
    deposit:0,
    money:0,
    // 续租
    TotalPrices:0,
    endTime: new Date().getTime() + 60 * 60 * 1000, // 预订结束时间，假设为一小时后
    countDownend: 20, // 倒计时文本
    isShow:false, // 初始化显示
    numes:0,
    value: "2023-10-25 15:11",
    totaltime:0,
    pay_type:2,//1余额2是微信
     // 第一种方法
     timeslot:[
        {name: '00:00', flag: false },
        { name: '01:00',flag: false },
        { name: '02:00',flag: false },
        { name: '03:00',flag: false },
        { name: '04:00',flag: true },
        { name: '05:00',flag: false },
        { name: '06:00',flag: false },
        { name: '07:00',flag: false },
        { name: '08:00',flag: true },
        { name: '09:00',flag: false },
        { name: '10:00',flag: false },
        { name: '11:00',flag: true },
        { name: '12:00',flag: false },
        { name: '13:00',flag: false },
        { name: '14:00',flag: false },
        { name: '15:00',flag: false },
        { name: '16:00',flag: false },
        { name: '17:00',flag: false },
        { name: '18:00',flag: false },
        { name: '19:00',flag: false },
        { name: '20:00',flag: false },
        { name: '21:00',flag: false },
        { name: '22:00',flag: false },
        { name: '23:00',flag: false },
        { name: '24:00',flag: false },
      ],
      timeRange: [
        { time: '09:00', isBooked: false },//false已预订，true没有预定
        { time: '10:00', isBooked: true },
        { time: '11:00', isBooked: false },
        { time: '12:00', isBooked: false },
        { time: '13:00', isBooked: true },
        { time: '14:00', isBooked: false },
        { time: '15:00', isBooked: false },
        { time: '16:00', isBooked: false },
        { time: '17:00', isBooked: true },
        { time: '18:00', isBooked: false }
      ],
      selectedTimeIndex: -1,
      shows:true,
      TimeIndex:'',

  },
    // 第一种方法
    onTimeTap(e) {
        const index = e.currentTarget.dataset.index;
        console.log(index,'index-------------')
        this.setData({
            TimeIndex:index,
          selectedTimeIndex: index
        });
      },
      onConfirm() {
        const selectedTime = this.data.timeRange[this.data.selectedTimeIndex].time;
        // 处理确认按钮点击事件
        console.log('Confirmed time: ' + selectedTime);
        // 关闭时间选择器
        this.closeTimePicker();
      },
      onCancel() {
          this.setData({
            shows:false
          })
        // 处理取消按钮点击事件
        // 关闭时间选择器
        this.closeTimePicker();
      },
      closeTimePicker() {
        // 关闭时间选择器的方法
      },
// 下面不是的
  see_details: function () {
    var seeDetails = this.data.seeDetails
    seeDetails = !seeDetails
    this.setData({
      seeDetails: seeDetails
    })
  },
  code: function(){
    wx.navigateTo({
      url: '/pages/pay_success/pay_success?order_id=' + this.data.order_id
    })
  },


   // 续费 
   renew: function () {
    wx.navigateTo({
      url: '/pages/account_chongzhi/account_chongzhi'
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.deposit = wx.getStorageSync('deposit');
    this.data.money = wx.getStorageSync('money');
       this.setData({
        money:this.data.money,
        deposit:this.data.deposit,
        totaltime:this.data.value
                });
    var order_id = options.order_id || 0;
    app.ajax({
      url: '/api/user/orderDetail',
      data: {
        order_id: order_id
      },
      success: res => {
        if(res.code == 1){
          this.setData({
            order_id: order_id,
            order: res.data,
            store_label:res.data.label,
            price:res.data.price,
            //clock_time:res.data.start+res.data.num*3600,
            clock_time:res.data.start,
          })
          let that = this
          setTimeout(()=>{
            that.countDown();
          },1000)
        }else{
          wx.showToast({
            title: res.msg,
            icon: 'none'
          })
        }
      }
    }, 1);

    this.data.order_id = order_id;
    //每10秒获取订单支付信息
    this.payTiming();

  },
//启动定时获取支付信息
payTiming:function(){
  this.payOrder(1,2);
  this.payinterval = setInterval(function () {
      this.payOrder(1,2);
  }.bind(this), 5000);
},
/**
    * @param {*} pay_type           //支付方式 1余额 2微信
    * @param {*} operation_type     //1支付 2获取账单
    */
   payOrder:function(pay_type,operation_type){
    //console.log(this.data.pay_type)
     app.ajax({
          url: '/api/user/pay',
          data: {
            order_id: this.data.order_id,
            coupon_id: this.data.coupon_id,
            pay_type: pay_type,
            operation_type:operation_type
          },
          success: res => {
              if (res.code == 1) {
                  if(operation_type == 2){
                     var bill_money = res.data.bill_list[0].money;
                     var pay_price = bill_money - this.data.coupon_sub;
                     var vip_sub = 0;
                     if (this.data.rate > 0) {
                         vip_sub = pay_price * (10 - this.data.rate) / 10;
                         vip_sub = vip_sub.toFixed(2);
                         vip_sub = parseFloat(vip_sub);
                     }
                     pay_price = pay_price - vip_sub;
                     var coupon_info = this.data.coupon_sub + vip_sub;
                     this.data.constantly_hour = res.data.bill_data.hours;
                     this.data.constantly_price = res.data.bill_list[0].money;
                     this.setData({
                         bill_create_time: res.data.bill_data.create_time,
                         constantly_hour: this.data.constantly_hour,
                         constantly_price: this.data.constantly_price,
                     });
                  }
              } else {
                //订单已经结束返回首页
                  if(res.data == 100){
                    wx.reLaunch({
                      url: '/pages/index/index'
                  })
                  clearInterval(this.payinterval);
                  }
                  wx.showToast({
                     title: res.msg,
                     icon: 'none'
                  })
              }
          }
     }, 1);
},

  
  getKeyInfo(lockId){
    if(!lockId || lockId == ''){
      wx.showToast({
        title:`开锁失败，设备ID错误`,
        icon: 'none'
      });return
    }
    app.ajax({
      url: '/api/user/getkeyInfo',
      data: {
        id:this.data.order.id,
        lockId:lockId
      },
      success: res => {
        if(res.code == 1){
          if(res.data.length === 0){
            wx.showToast({
              title:res.data.msg,
              icon: 'none'
            });return
          }
          this.setData({
            keyInfo: res.data,
           });
          // wx.setStorageSync('roompassword_orderid_'+res.data.id, res.data.data.password);
          // this.checkRoomPass()
        }else{
          wx.showToast({
            title: '获取失败',
            icon: 'none'
          })
        }
      }
    }, 1);
  },
  // 获取房间密码
  getRoomPass:function(){
    if(this.data.order.lock_code =="" || this.data.order.lock_code==null){
      wx.showToast({
        title: "参数错误1",
        icon: 'none'
      })
      return
    }
    if(this.data.order.end =="" || this.data.order.end==null){
      wx.showToast({
        title: "参数错误2",
        icon: 'none'
      })
      return
    }
    app.ajax({
      url: '/api/user/getRoomPassword',
      data: {
        lock_code: this.data.order.lock_code,
        use_end_time: this.data.order.end,
        mac_code:this.data.order.mac_code
      },
      success: res => {
        if(res.code == 1){
          if(res.data.data.length === 0){
            wx.showToast({
              title:res.data.msg,
              icon: 'none'
            });return
          }
          this.setData({
            room_password: res.data.data.password,
           });
          wx.setStorageSync('roompassword_orderid_'+res.data.id, res.data.data.password);
          this.checkRoomPass()
        }else{
          wx.showToast({
            title: '获取失败',
            icon: 'none'
          })
        }
      }
    }, 1);
  },
  //点击复制密码
  checkRoomPass: function () {
    var that = this;
    wx.showModal({
      title: '房间密码',
      content: that.data.room_password,
      showCancel: true,
      confirmText: '复制密码',
      success(res) {
        if (res.confirm) {
          wx.setClipboardData({
            data: that.data.room_password,
            success(res) {
              wx.getClipboardData({
                success(res) {
                  console.log(res.data) // data
                  wx.showToast({
                    title: "复制成功",
                    icon: 'none'
                  })
                },fail(res){
                  wx.showToast({
                    title: "复制失败",
                    icon: 'none'
                  })
                }
              })
            }
          })
        }
      }
    })
  },
    //倒计时函数
    countDown:function(){
      //倒计时
     // 1624550400
     var timestamp = Date.parse(new Date());  
     timestamp = timestamp / 1000;  
     console.log("当前时间戳为：" + timestamp);  
     if(this.data.clock_time<=0){
      return
    }
     console.log(this.data.clock_time)
     //var totalSecond = (Date.parse(new Date()) / 1000) - (Date.parse(this.data.clock_time) / 1000) + 2;
     var totalSecond = (Date.parse(new Date()) / 1000) - this.data.clock_time + 2;
     this.interval = setInterval(function () {
        // 秒数
        var second = totalSecond;
        // 天数位
        var day = Math.floor(second / 3600 / 24);
        var dayStr = day.toString();
        if (dayStr.length == 1) dayStr = '0' + dayStr;
        // 小时位
        var hr = Math.floor((second - day * 3600 * 24) / 3600);
        var hrStr = hr.toString();
        if (hrStr.length == 1) hrStr = '0' + hrStr;
        // 分钟位
        var min = Math.floor((second - day * 3600 *24 - hr * 3600) / 60);
        var minStr = min.toString();
        if (minStr.length == 1) minStr = '0' + minStr;
        // 秒位
        var sec = second - day * 3600 * 24 - hr * 3600 - min*60;
        var secStr = sec.toString();
        if (secStr.length == 1) secStr = '0' + secStr;
        this.setData({
        countDownDay: dayStr,
        countDownHour: hrStr,
        countDownMinute: minStr,
        countDownSecond: secStr,
        });
        totalSecond++;
        if (totalSecond < 0) {
        clearInterval(this.interval);
        // wx.showToast({
        //   title: '未开始',
        // });
        this.setData({
          countDownDay: '00',
          countDownHour: '00',
          countDownMinute: '00',
          countDownSecond: '00',
          fw_status:false
        });
        }
      }.bind(this), 1000);
 },
  getList: function(){

  },
  handleChange: function(e) {
    console.log(e)
    this.setData({
      value: e.detail.date
    })
    　var dateTimeStr = this.data.value;
    　　const date = new Date(dateTimeStr);
    　　const timestamp = date.getTime()+ Number(this.data.numes*3600000);
        this.sliderchange(timestamp)
},
setPayType: function (e) {
    var type = e.currentTarget.dataset.type;
    this.setData({
        pay_type: type
    })
},
account_chongzhi: function () {
    wx.navigateTo({
        url: '/pages/account_chongzhi/account_chongzhi',
    })
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
 
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log('我显示了');
        //倒计时延迟2秒才行
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
      clearInterval(this.payinterval);
      clearInterval(this.interval);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
      clearInterval(this.payinterval);
      clearInterval(this.interval);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
   * 结算
   */
  checkOutRoom:function(e){
    var room_id = e.target.dataset.room_id;
    // console.log(room_id)
    // if(!room_id) {
    //   wx.showToast({
    //     title: '退房提交失败',
    //     icon: 'none'
    //   });
    //   return false;
    // }
    app.ajax({
      url: '/api/user/checkOutRoom',
      data: {
        room_id:  room_id
      },
      success: res => {
        if(res.code == 1){
          setTimeout(function(){
            wx.navigateBack({
                  delta: 1,
                })
            }, 1500);
        }
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    }, 1);
  },
  unsettled:function(e){
    var order_id = e.target.dataset.order_id;
    if(!order_id) {
      wx.showToast({
        title: '退房提交失败',
        icon: 'none'
      });
      return false;
    }
    wx.navigateTo({
      url: '/pages/unsettled/unsettled?order_id=' + order_id
    })
  },
  goods:function(){
    wx.navigateTo({
      url: '/pages/book/book'
    })
  },
  power:function(e){
    //var mac_code = e.target.dataset.mac_code;
    var mac_code = this.data.order.mac_code;
    console.log(mac_code)
    if(!mac_code){
      wx.showToast({
        title: '通电失败',
        icon: 'none'
      });
      return false;
    }
    app.ajax({
      url: '/api/user/roomPowerOn',
      data: {
        mac_code:  mac_code,
        is_source:1,//用户手动开电
      },
      success: res => {
        if(res.code == 2){
          wx.showToast({
          title: res.msg,
          icon: 'none'
        })
        wx.navigateTo({
          url: '/pages/index/index',
        })
        }
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    }, 1);
  },
  //开锁和闭锁
  room_lock:function(type){
    app.ajax({
      url: '/api/user/roomLockState',
      data: {
        id:  this.data.order.id,
        lockId:this.data.order.lockId,
        state:this.data.lock_state,
        type:type
      },
      success: res => {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    }, 1);
  },
  /**
   * 换房
   */
  exchangeHouses:function(e){
    var store_id = e.target.dataset.store_id,room_id = e.target.dataset.room_id;
    console.log(store_id)
    var list = '';
    app.ajax({
      url: '/api/index/getRoomList',
      data: {
        store_id: store_id,
        room_id:room_id
      },
      success: res => {
        if(res.code == 1){
          list = res.data;
        }
        this.setData({
          RoomList:list,
          showModalStatus:true
        });
      }
    })

  },
// 续租
    btnOk:function(){
        this.setData({
            isShow: !this.data.isShow, // 切换显示状态
          });
   
    },
    slider3change:function(e){
        this.setData({
            TotalPrices:e.detail.value*this.data.price,
            numes: e.detail.value
        })
    //     var Largetime=this.data.select_date+`ms${this.data.spaces}`+this.data.time 
    //     Largetime= Largetime.replace('ms','\t')
    // 　　var date = new Date(Largetime);
    // 　　var timestamp = date.getTime();
    //     timestamp=timestamp+e.detail.value*3600000

      　var dateTimeStr = this.data.value;
    　　const date = new Date(dateTimeStr);
    　　const timestamp = date.getTime()+ Number(e.detail.value*3600000);
        this.sliderchange(timestamp)
        console.log(e.detail.value,timestamp,'e---------')
    },
    sliderchange:function(e){
        var date = new Date(e); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var Y = date.getFullYear() + '-';
        var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
        var h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':';
        var m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()) ;
        this.data.totaltime=Y + M + D + h + m 
        this.setData({
            totaltime: this.data.totaltime
        })
    },
    cancellation(){
        this.setData({
            isShow:false
          });
    },
    // getData(n){
    //  let   n=new Date(n)
    //     return n.toLocaleDateString().replace(/\//g, "-") + " " + n.toTimeString().substr(0, 8)
    //   },
    determine(){
        // this.getData(Date.now())
        var dateTimeStr = this.data.value;
    　　const date = new Date(dateTimeStr);
       const timestamp = date.getTime()
        if(timestamp<Date.now()){
         return   wx.showToast({
                title: '选择的时间不能小于当前的时间',
                icon: 'none'
            });
        }

        
    },
  close:function(){
    this.setData({
      showModalStatus:false
    });
  },
  book:function(e) {

    wx.showModal({
      title: '',
      content: '是否确认换房，将会产生换房费用',
      success: (res) =>  {
    
       if (res.confirm) {
        var room_id = e.target.dataset.room_id;
        var order_id = e.target.dataset.order_id;
        if(!room_id && !order_id){
          wx.showToast({
            title: '参数错误',
            icon: 'none'
          })
        }


        app.ajax({
          url: '/api/user/exchangeHouses',
          data: {
            room_id: room_id,
            order_id: order_id
          },
          success: res => {
            if(res.code == 1){
              wx.showToast({
                title: res.msg,
                icon: 'none'
              });

              this.setData({
                showModalStatus:false
              });
              setTimeout(function(){
                  // wx.navigateBack({
                  //   delta: 1,
                  // })
                  // wx.navigateTo({
                  //   url: '/pages/opening_code/opening_code?order_id=' + order_id
                  // })
                  wx.redirectTo({
                    url: '/pages/opening_code/opening_code?order_id=' + order_id
                  })
              }, 3000);
            }else{
              wx.showToast({
                title: res.msg,
                icon: 'none'
            });

               if (res.code == 301) {

                //倒计时延迟2秒才行
                setTimeout(()=>{
                    wx.navigateTo({
                        url: '/pages/account_chongzhi/account_chongzhi'
                    })
                },1000)

                }
             
            }
          }
        })
       } else if (res.cancel) {
        console.log('用户点击取消')
        return false
       }
      }
     })
  }
})